"use client";

import Image from "next/image";
import style from "./index.module.scss";
import { useRef } from "react";
import { useEventListener } from "ahooks";
import { getWordTemplate } from "@/service/oldResume";
import { useCommonStore } from "@/src/providers/common-store-provider";
import Link from "next/link";

function Index({ list }) {
  const { wordList, setWordList } = useCommonStore((state) => {
    return {
      ...state,
      wordList: state.wordList.length ? state.wordList : list,
    };
  });

  const pagerRef = useRef({ pageNum: 1 });
  const hasFinish = useRef(false);
  const loading = useRef(false);
  const scroll = (e) => {
    if (hasFinish.current || loading.current) return;
    var scrollHeight = Math.max(
      document.documentElement.scrollHeight,
      document.body.scrollHeight
    );
    //滚动条滚动距离
    var scrollTop =
      document.documentElement.scrollTop || document.body.scrollTop;
    //窗口可视范围高度
    var clientHeight =
      window.innerHeight ||
      Math.min(
        document.documentElement.clientHeight,
        document.body.clientHeight
      );

    if (clientHeight + scrollTop >= scrollHeight) {
      console.log("===加载更多内容……===");
      pagerRef.current.pageNum++;
      getList();
    }
  };

  useEventListener("scroll", scroll);

  const getList = async () => {
    loading.current = true;
    const res = await getWordTemplate({
      pageNum: pagerRef.current.pageNum,
      pageSize: 20,
    });
    loading.current = false;
    if (res.code === 200) {
      if (res.data.data?.length) {
        setWordList([...wordList, ...(res.data.data || [])]);
      } else {
        hasFinish.current = true;
      }
    }
  };
  return (
    <ul className={style.list}>
      {wordList.map((item, index) => {
        return (
          <li key={item.id} className={style.listItem}>
            <Link href={`/word/${item.id}`}>
              <div className={style.img}>
                <div className={style.cover}>
                  <div className={style.button}>使用模板</div>
                </div>
                <Image
                  src={item.template_img + "?imageView2/2/w/800"}
                  alt={item.template_name}
                  title={item.template_name}
                  fill
                />
              </div>
              <div className={style.info}>
                <h4 className={style.name}>{item.template_name}</h4>
              </div>
            </Link>
          </li>
        );
      })}
    </ul>
  );
}

export default Index;
